//index.js  
//获取应用实例  
var app = getApp();
Page({
  data: {
    getDataFlag:true,//是否继续获取数据的开关
    // showDataFlag: true,//是否继续显示数据的开关
    timer:1,
    wendu:'',
    xinlv:'',
    xueyang:'',
    jieshou:"",
    status: "",
    sousuo: "",
    sousuoya:"",
    suzhangya:"",
    connectedDeviceId: "", //已连接设备uuid  
    services: "", // 连接设备的服务  
    characteristics: "",   // 连接设备的状态值  
    writeServicweId: "", // 可写服务uuid  
    writeCharacteristicsId: "",//可写特征值uuid  
    readServicweId: "", // 可读服务uuid  
    readCharacteristicsId: "",//可读特征值uuid  
    notifyServicweId: "", //通知服务UUid  
    notifyCharacteristicsId: "", //通知特征值UUID  
    inputValue: "",
    characteristics1: "", // 连接设备的状态值  
  },
  onLoad: function () {
    // this.analysisData();
    if (wx.openBluetoothAdapter) {
      wx.openBluetoothAdapter()
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示  
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //开始连接  
  lanya1: function () {
    var that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.showLoading({
          title:'开启蓝牙适配器',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        //搜索设备
        wx.startBluetoothDevicesDiscovery({
          services: ['FEE0'],
          allowDuplicatesKey:false,
          success: function (res) {
            console.info('开启搜索周边设备');
            console.info('开启搜索周边设备',res);
            wx.hideLoading();
            wx.showLoading({
              title: '开启搜索周边设备',
            })
              //显示可以连接的设备
            wx.getBluetoothDevices({
              success: function (res) {
                wx.hideLoading();
                if (res.devices==""){
                  wx.showToast({
                    title: '没有设备,请重试',
                  })
                }
                console.info("可以连接的设备", res.devices);
                //是否有已连接设备  
                wx.getConnectedBluetoothDevices({
                  success: function (res) {
                    that.setData({
                      connectedDeviceId: res.deviceId,
                    })
                  
                  }

                })
                that.setData({
                devices: res.devices
                })
              }
            })
          }
        })
      },
      fail:function(){
        wx.showToast({
          title: '请开启蓝牙设备',
        })
        // this.lan1();
        this.lanya0();

      }
    })
  },

  //连接设备  
  connectTO: function (e) {
    //先停止搜索
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止搜索设备");
      }
    })
    var that = this;
    wx.createBLEConnection({
      deviceId: e.currentTarget.id,
      success: function (res) {
        that.setData({
          connectedDeviceId: e.currentTarget.id
        }),
      wx.getBLEDeviceServices({
        deviceId: that.data.connectedDeviceId,
        success: function(res) {
          that.setData({
             services:res.services
           })
          console.info("获取服务的uuid",that.data.services[0]);
          wx.getBLEDeviceCharacteristics({

            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取  
            deviceId: that.data.connectedDeviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取  
            serviceId: that.data.services[0].uuid,
            success: function (res) {
              console.info("characteristics属性值",res.characteristics);
                wx.notifyBLECharacteristicValueChange({
                  deviceId: that.data.connectedDeviceId,
                  serviceId: that.data.services[0].uuid,
                  characteristicId: res.characteristics[1].uuid,
                  state: true,
                  success: function (res) {
                    wx.onBLECharacteristicValueChange(function (characteristic) {
                      console.info("接受===",characteristic);
                      let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');
                      console.info("测量的值为:",hex);
                      // that.analysisData(hex);
                      //去掉前10次数据 取10--20次的平均值
                       var map=that.analysisData(hex);
                      //  wx.setStorageSync(that.data.timer.toString(), map);
                       console.info(map);
                       that.data.timer=that.data.timer+1;
                       console.info(that.data.timer);
                      //  if (that.data.timer % 5==0){
                        //  console.info('数据收集完成');
                         //计算值只返回一个map并且上传数据
                         //判断是否进入上传状态
                       if (that.data.getDataFlag) {
                         if (that.checkData(map)){
                           //判断上传状态//成功则进入等待状态2分钟之后 重复上述操作
                           console.info("==============数据正确,可以上传===============");
                             var returnFlag=that.sendMessage(map);
                             //上传成功进入延时器，失败则继续前面的操作
                             if (returnFlag){
                               that.setData({
                                 getDataFlag:false
                               });
                                that.goToSendData();
                             }
                           }        
                         }

                    });

                  },
                  fail: function (res) {
                    console.info('开启notifiy失败',res);
                  },
                  complete: function (res) {
                    
                  }
                })
              
              
            },
            fail: function () {
              console.log("fail");
            },
            complete: function () {
              console.log("complete");
            }
          })
        },
      })
     
      },
      fail: function () {
        console.log("调用失败");
        // that.lanya5();
      },
      complete: function () {
        // that.lanya5();
      }

    })
    console.log(that.data.connectedDeviceId);
  },
  //断开设备连接  
  lanya0: function () {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.connectedDeviceId,
      success: function (res) {
        that.setData({
          connectedDeviceId: "",
        })
      }
    })
  },
  //断开适配器连接
  lan1:function(){
    wx.closeBluetoothAdapter({
      success: function (res) {
        console.log(res)
      }
    })
  },
  sendMessage:function(map){
   var  returnFlag=true;
    //value即为hex的值
    var that=this;
    var data = {
      "type": "insertGeneralInspectData",
      "code": 'xinlv',
      "value":map['xinlv'],
      'user_id': parseInt(app.globalData.id),
      'inspect_date': new Date().getTime(),
    }

    var data1={
      "type": "insertGeneralInspectData",
      "code": 'xueyang',
      "value": map['xueyang'],
      'user_id': parseInt(app.globalData.id),
      'inspect_date': new Date().getTime(),
    }

    var data2 = {
      "type": "insertGeneralInspectData",
      "code": 'wendu',
      "value": map['wendu'],
      'user_id': parseInt(app.globalData.id),
      'inspect_date': new Date().getTime(),
    }

    var  data3={
      "type": "insertGeneralInspectData",
      "code": 'sousuoya',
      "value": map['sousuoya'],
      'user_id': parseInt(app.globalData.id),
      'inspect_date': new Date().getTime(),

    }

    var data4 = {
      "type": "insertGeneralInspectData",
      "code": 'suzhangya',
      "value": map['suzhangya'],
      'user_id': parseInt(app.globalData.id),
      'inspect_date': new Date().getTime(),
    }

      //从缓存数据中取出之前的code
    app.func.reqForTiePian(data, function (res) {
      console.info(res);
      console.info("上传心率");
      if (res.code == "1") { 
        returnFlag = true;
      } else {
        returnFlag=false;
      }
     
    });

    //从缓存数据中取出之前的code
    app.func.reqForTiePian(data1, function (res) {
      console.info("上传数据血氧", res);
      if (res.data.code == "1") {
        returnFlag = true;
      } else {
        returnFlag = false;

      }
    });
    //从缓存数据中取出之前的code
    app.func.reqForTiePian(data2, function (res) {
      console.info("上传数据温度", res);
      if (res.data.code == "1") {
        returnFlag = true;
      } else {
        returnFlag = false;
      }
    });

    //从缓存数据中取出之前的code
    app.func.reqForTiePian(data3, function (res) {
      console.info("上传收缩压", res);
      if (res.data.code == "1") {
        returnFlag = true;
      } else {
        returnFlag = false;
      }
    });

    //从缓存数据中取出之前的code
    app.func.reqForTiePian(data4, function (res) {
      console.info("上传数据舒张压", res);
      if (res.data.code == "1") {
        if (returnFlag) {
          that.setData({
            getDataFlag:false
          });
          wx.showToast({
            title: res.data.message
          })
        }
      } else {
        wx.showToast({
          title: "上传失败"
        })
        wx.hideLoading();
      }
    });
   
    return returnFlag;
  },
  //监听input表单  
  analysisData:function(e){
    if (!this.data.getDataFlag){
      return;
    }
    //aa32372e30303531303832bb 去掉aa 和bb"aa32372e30303531303832bb"
    var data = e;
    data=data.substring(2, data.length-2);
    var wendu = this.hexCharCodeToStr(data.substring(0,8));
    var xinlv = this.hexCharCodeToStr(data.substring(8,14));
    var xueyang = parseInt(this.hexCharCodeToStr(data.substring(14,21)));
    if (wendu != "" || wendu != null || wendu!='Nan'){
      var sousuoya = app.func.randomNum(125, 140);
      var suzhangya = app.func.randomNum(80, 90);
    }
    this.setData({
      wendu: wendu,
      xinlv: xinlv,
      xueyang: xueyang,
      sousuoya: sousuoya,
      suzhangya: suzhangya
    })
    
    //返回数据
    var map={};
    map["wendu"] = wendu;
    map["xinlv"] = xinlv;
    map["xueyang"] = xueyang;
    map["sousuoya"] = sousuoya;
    map["suzhangya"] = suzhangya;
    return map;
  },
//16转字符串
  hexCharCodeToStr :function(hexCharCodeStr) {
  　　var trimedStr = hexCharCodeStr.trim();
  　　var rawStr =
    　　trimedStr.substr(0, 2).toLowerCase() === "0x"
      　　?
      　　trimedStr.substr(2)
      　　:
      　　trimedStr;
  　　var len = rawStr.length;
  　　if (len % 2 !== 0) {
    　　　
    　　　　return "";
  　　}
  　　var curCharCode;
  　　var resultStr = [];
  　　for (var i = 0; i < len; i = i + 2) {
    　　　　curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
    　　　　resultStr.push(String.fromCharCode(curCharCode));
  　　}
  　　return resultStr.join("");
},
  //检测数据是否合理
 checkData:function(map){
   var getData = '';
   var dataType = '';
   var returnFlag = false;
   var xinlvflag = false;
   var xueyangflag = false;
   var wenduflag = false;
   for (let key in map){
     getData = map[key];
     if (getData == null || getData == "null" || typeof (getData) == "undefined" ){
       return  false;
     }
     dataType = key;
     console.info('key', key);
     console.info('value', map[key]);
     var gettype = Object.prototype.toString;
     //1.判断所有的数据都不为null和0和负数
     if (app.func.checkData(getData)){
       //根据数据类型来判断是否属于阈值内的数据
       if (dataType == "xinlv") {
         console.info("开始检测数据类型")
         console.info( gettype.call(dataType));
         console.info(parseInt(getData)); 
         console.info("结束检测数据类型");

         if (parseInt(getData) >= app.globalData.xinlvshang && parseInt(getData) <= app.globalData.xinlvxia) {
           xinlvflag = true;
         } else {
           xinlvflag = false;
           continue;
         }
       } else if (dataType == "xueyang") {
         console.info(parseInt(getData));
         if (parseInt(getData) >= app.globalData.xueyangshang && parseInt(getData) <= app.globalData.xueyangxia) {
           xueyangflag = true;
         } else {
           xueyangflag = false;
           continue;
         }
       } else if (dataType == "wendu"){
         console.info(parseInt(getData));
         if (parseInt(getData) >= app.globalData.wendushang && parseInt(getData) <= app.globalData.wenduxia) {
           wenduflag = true;
         } else {
           wenduflag = false;
           continue;
         }
       }
     } else {
       returnFlag = false;
       continue;
     }
   }
   if (xinlvflag && xueyangflag 　&& wenduflag){
     returnFlag=true;
   }
   console.info('校验参数结果', returnFlag)
   return returnFlag;
 },
 //60000
 goToSendData:function(){
   var that=this;
   setTimeout(function(){
     that.setData({
       getDataFlag:true
     })
   }, 60000)
 }

})  